package com.xls.boxlibrary.duihuanjibi;

import static com.xls.commonlibrary.constant.Const.MMKV_IS_UPDATE_GAME;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_TIXIAN_SHOWQUAN_OK;

import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;


import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xls.boxlibrary.Consts.IntentConsts;
import com.xls.boxlibrary.adapter.DuiHuanJiBiTabAdapter;
import com.xls.boxlibrary.adapter.DuiHuanJinBiBiLiAdapter;
import com.xls.boxlibrary.adapter.MvpBaseRecyclerAdapter;
import com.xls.boxlibrary.dilog.ErrDialog;
import com.xls.boxlibrary.dilog.OkDialog;
import com.xls.boxlibrary.entity.AppsRulesEntity;
import com.xls.boxlibrary.entity.DuiHuanJiBiInfoEntity;
import com.xls.boxlibrary.entity.JiFenMingXiEntity;
import com.xls.boxlibrary.entity.JiFenTiXianBiliEntity;
import com.xls.boxlibrary.entity.UserEntity;
import com.xls.boxlibrary.mvp.BasePresenterImpl;
import com.xls.boxlibrary.network.RequestCallBack;
import com.xls.boxlibrary.network.RequestCallBackTwo;
import com.xls.boxlibrary.utils.AppUtils;
import com.xls.boxlibrary.utils.SPUtils;
import com.xls.boxlibrary.utils.TUtils;
import com.xls.commonlibrary.http.CallbackT;
//import com.xls.commonlibrary.risk.RiskUtil;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.eventbus.ConstEventBus;
import com.xls.commonlibrary.util.LoginUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;
import com.xls.commonlibrary.wxapi.ConstWx;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * MVPPlugin
 */

public class DuiHuanJiBiPresenter extends BasePresenterImpl<DuiHuanJiBiContract.View> implements DuiHuanJiBiContract.Presenter{


    DuiHuanJiBiTabAdapter adapter;
    ArrayList<AppsRulesEntity> datalist=new ArrayList<>();
    @Override
    public RecyclerView.Adapter getAdapter() {
        if (adapter==null){
            adapter=new DuiHuanJiBiTabAdapter(context, datalist, new MvpBaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    for (AppsRulesEntity appsRulesEntity:datalist){
                        appsRulesEntity.setSelector(false);
                    }
                    if (datalist.get(position).getExchangeCount()>0){
                        datalist.get(position).setSelector(true);
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        }
        return adapter;
    }
    String appsRulesId="";
    String exchangeValue="";
    @Override
    public void duihuan() {

        for (AppsRulesEntity appsRulesEntity:datalist){
            if (appsRulesEntity.isSelector()){
                appsRulesId=appsRulesEntity.getId();
                exchangeValue=appsRulesEntity.getExchangeValue();
            }
        }
        if (TextUtils.isEmpty(appsRulesId)){
            mView.getTiXianBtn().setEnabled(true);
            TUtils.showShort(context,"请选择提现额度");
            return;
        }
        getPermissions("game_duihuanjinbi",new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
                getScoreExchange();
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });

    }

    private void getScoreExchange(){
        JinBiNetWorkUtil.getInstance().getScoreExchange(context,appsRulesId, getType(),getAPPId(),getPackageName(), new RequestCallBackTwo<DuiHuanJiBiInfoEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(DuiHuanJiBiInfoEntity requestData, String msg) {
                if (activity==null||mView==null)return;
                coinsExchange(exchangeValue,requestData);

                MMKVUtil.getInstance().getKV().encode(MMKV_IS_UPDATE_GAME, true);
            }

            @Override
            public void onRequestfail(String errno, Object errmsg) {
                mView.getTiXianBtn().setEnabled(true);
                if (TextUtils.equals("200",errno)){

                    MMKVUtil.getInstance().getKV().encode(MMKV_IS_UPDATE_GAME, true);
                    updata();
                    DuiHuanJiBiInfoEntity requestData= (DuiHuanJiBiInfoEntity) errmsg;
                    OkDialog okDialog=new OkDialog(context, "提现"+exchangeValue+"元成功！\n 审核通过后，奖励 "+requestData.getSubsidyScoreStr()+" 元宝");
                    okDialog.show();
                }else {
                    ErrDialog errDialog=new ErrDialog(context, (String) errmsg);
                    errDialog.show();
                }
            }
        });
    }

    @Override
    public void getPermissions(String source, RequestCallBack<String> callBack) {
        XXPermissions.with(activity)
                // 申请单个权限
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                .permission(Permission.READ_PHONE_NUMBERS)
//                .permission(Permission.READ_PHONE_STATE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            LoginUtil.getInstance().getLoginParams2(activity, new CallbackT<Map<String, String>>() {
                                @Override
                                public void callback(Map<String, String> stringStringMap) {
                                    stringStringMap.put("appName", AppUtils.getPackageName(activity));
                                    stringStringMap.put("token", SPUtils.getLoginToken(context));

                                    stringStringMap.put("withdrawal_amount",exchangeValue);
//                                    RiskUtil.getInstance().reportRisk("withdrawal");
                                    
                                    fkCheck(source,stringStringMap,callBack);
                                }
                            });
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            XXPermissions.startPermissionActivity(activity, permissions);
                        } else {
                            TUtils.showShort(context,"请授予权限,并重新登陆");
                            LoginUtil.getInstance().outLogin(activity);
                        }
                    }
                });
    }

    @Override
    public void getOauthConfig() {
        JinBiNetWorkUtil.getInstance().getOauthConfig(context, new RequestCallBack<JinBiNetWorkUtil.HuiFuData>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(JinBiNetWorkUtil.HuiFuData requestData) {
                if (requestData==null){
                    TUtils.showShort(context,"无法提现");
                    return;
                }
                if (!TextUtils.equals(requestData.is_auth,"1")){
                    String appId = ConstWx.wxAppId; // 填移动应用(App)的 AppId，非小程序的 AppID
                    IWXAPI api = WXAPIFactory.createWXAPI(context, appId);
                    WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                    req.userName = requestData.gh_id; // 填小程序原始id
                    req.path = requestData.path+"?"+requestData.query;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                    api.sendReq(req);
                }else {
                    EventBus.getDefault().post(new MessageEvent(EVENT_TIXIAN_SHOWQUAN_OK, ""));
                }
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
    }

    private void fkCheck(String source,Map<String, String> stringStringMap, RequestCallBack<String> callBack) {
        JinBiNetWorkUtil.getInstance().fkCheck(activity,source,stringStringMap,callBack);
    }

    private void coinsExchange(String score, DuiHuanJiBiInfoEntity duiHuanJiBiInfoEntity) {
        JinBiNetWorkUtil.getInstance().coinsExchange(context,score, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
                if (mView==null||context==null)return;
                OkDialog okDialog=new OkDialog(context,"提现"+score+"元成功！\n 奖励 "+duiHuanJiBiInfoEntity.getSubsidyScoreStr()+" 元宝");
                okDialog.show();
                updata();
                EventBus.getDefault().post(new MessageEvent(ConstEventBus.EVENT_BOX_WITHDRAWAL,""));
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                mView.getTiXianBtn().setEnabled(true);
                ErrDialog errDialog=new ErrDialog(context,errmsg);
                errDialog.show();
            }
        });
    }

    public String getType() {
        return activity.getIntent().getStringExtra(IntentConsts.type);
    }

    public String getAPPId(){
        return activity.getIntent().getStringExtra(IntentConsts.id);
    }

    public String getPackageName(){
        return activity.getIntent().getStringExtra(IntentConsts.packageName);
    }

    public void updata(){
        JinBiNetWorkUtil.getInstance().getAccountByAppId(context,getAPPId(),getPackageName(), new RequestCallBack<JiFenMingXiEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(JiFenMingXiEntity requestData) {
                if (mView==null||requestData==null||context==null)return;
                mView.showData(requestData);
                getUserLevel(requestData);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
        JinBiNetWorkUtil.getInstance().getAppRules(context,getAPPId(),getPackageName(), new RequestCallBack<ArrayList<AppsRulesEntity>>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(ArrayList<AppsRulesEntity> requestData) {
                if (activity==null||context==null||getView()==null)return;
                datalist.clear();
                datalist.addAll(requestData);
                adapter.notifyDataSetChanged();
                if (datalist.size()==0){
                    mView.showTiXianBtnState(false);
                }else {
                    mView.showTiXianBtnState(true);
                }
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
    }


    public void  getScoreExchangeRateRules(String level){
        JinBiNetWorkUtil.getInstance().getScoreExchangeRateRules(context,getAPPId(),getPackageName(), new RequestCallBack<ArrayList<JiFenTiXianBiliEntity>>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(ArrayList<JiFenTiXianBiliEntity> requestData) {
                if (activity==null||getView()==null||context==null||requestData==null)return;
                for (JiFenTiXianBiliEntity jiFenTiXianBiliEntity:requestData){
                    if (TextUtils.equals(jiFenTiXianBiliEntity.getLevel(),level))jiFenTiXianBiliEntity.setSelector(true);
                }
                jiFenTiXianBiliEntities.clear();
                jiFenTiXianBiliEntities.addAll(requestData);
                duiHuanJinBiBiLiAdapter.notifyDataSetChanged();

            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });

    }

    private void getUserLevel(JiFenMingXiEntity jiFenMingXiEntity){
        JinBiNetWorkUtil.getInstance().getUserLevel(context,getAPPId(),getPackageName(), new RequestCallBack<UserEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(UserEntity requestData) {
                if (activity==null||getView()==null||context==null||requestData==null)return;
                mView.showLevel(requestData,jiFenMingXiEntity);
                getScoreExchangeRateRules(requestData.getLevel());
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
    }

    DuiHuanJinBiBiLiAdapter duiHuanJinBiBiLiAdapter;
    ArrayList<JiFenTiXianBiliEntity> jiFenTiXianBiliEntities=new ArrayList<>();
    public RecyclerView.Adapter getBiliAdapter() {
        if (duiHuanJinBiBiLiAdapter==null){
            duiHuanJinBiBiLiAdapter=new DuiHuanJinBiBiLiAdapter(context,jiFenTiXianBiliEntities);
        }
        return duiHuanJinBiBiLiAdapter;
    }
}
